package com.powerNode.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.powerNode.config.WhiteList;
import com.powerNode.constant.AuthConstant;
import com.powerNode.enums.StatusEnmu;
import com.powerNode.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.Date;
import java.util.List;

/**
 * @description:
 * @author: mky
 * @date: 2024/9/14 16:23
 * @version: 1.0
 */
@Component
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {
    @Autowired
    private WhiteList whiteList;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().toString();
        List<String> whiteListStr = whiteList.getWhiteList();
        if (whiteListStr.contains(path)){
            //放行
            return chain.filter(exchange);
        }else {
            //拦截
            //判断请求头有没有token，没有接返回登录页
            String token = request.getHeaders().getFirst(AuthConstant.AUTHORIZATION);
            if (StringUtils.hasText(token)){
                String tokenValue = token.replaceFirst(AuthConstant.BEARER, "");
                //看redis有吗
                if (redisTemplate.hasKey(tokenValue)){
                    return chain.filter(exchange);
                }
            }
        }
        //其他情况全部拦截，报错
        log.error("非法请求，拦截时间：{}，请求api：{}",new Date(),path);
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().set("Content-Type", "application/json");
        Result<Object> result = Result.fail(StatusEnmu.ILLEGAL_REQUEST);
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] bytes = new byte[0];
        try {
            bytes = objectMapper.writeValueAsBytes(result);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        DataBuffer wrap = response.bufferFactory().wrap(bytes);

        return response.writeWith(Mono.just(wrap));
    }

    @Override
    public int getOrder() {
        return -5;
    }
}
